package com.boomsecret.zookeeper;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.apache.curator.framework.recipes.locks.InterProcessReadWriteLock;
import org.apache.curator.retry.ExponentialBackoffRetry;

/**
 * Created by wangjinliang on 2018/8/6.
 */
public class WriteReadLockDemo {
    private static final int RETRY_TIME = 1000;
    private static final int RETRY_TIMES = 3;

    public static void main(String[] args) {
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(RETRY_TIME, RETRY_TIMES);
        CuratorFramework client = CuratorFrameworkFactory.newClient("182.92.234.232:2181", retryPolicy);
        client.start();

        InterProcessReadWriteLock readWriteLock = new InterProcessReadWriteLock(client, "/read_write_lock");
        InterProcessMutex readLock = readWriteLock.readLock();
//        InterProcessMutex writeLock = readWriteLock.writeLock();
        InterProcessMutex readLock2 = readWriteLock.readLock();
        try {
            readLock.acquire();
            System.out.println(Thread.currentThread().getName() + "获取到读锁");
            new Thread(() -> {
                try {
//                    writeLock.acquire();
//                    System.out.println(Thread.currentThread().getName() + "获取到写锁");

                    readLock2.acquire();
                    System.out.println(Thread.currentThread().getName() + "获取到读锁");
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    try {
//                        writeLock.release();
//                        System.out.println(Thread.currentThread().getName() + "释放到写锁");

                        readLock2.release();
                        System.out.println(Thread.currentThread().getName() + "释放到读锁");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

            }).start();
            Thread.sleep(3000);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                readLock.release();
                System.out.println(Thread.currentThread().getName() + "释放到读锁");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        client.close();
    }
}
